from random import uniform

import pyglet
from pyglet.gl import *

import interface as libswarm

class _Demo(pyglet.window.Window):
	def __init__(self, width, height):
		config = None
		for template_config in (
		 pyglet.gl.Config(double_buffer=True, depth_size=0, sample_buffers=1, samples=4),
		 pyglet.gl.Config(double_buffer=True, depth_size=0, sample_buffers=1, samples=2),
		 pyglet.gl.Config(double_buffer=True, depth_size=0)
		):
			try:
				config = pyglet.window.get_platform().get_default_display().get_default_screen().get_best_config(template_config)
				break
			except pyglet.window.NoSuchConfigException:
				pass
		if not config:
			raise pyglet.window.NoSuchConfigException('Unable to configure display.')
			
		pyglet.window.Window.__init__(
			self,
			width=width, height=height,
			config=config, resizable=False, fullscreen=False, vsync=True
		)
		
		self._bg_layer = libswarm.World(
		 width, height, 9999,
		 (
		  (
		   'red', libswarm.EnergyBall, 100,
		   8, 2.5,
		   (0.9, 0.0, 0.0), (0.8, 0.0, 0.0), 100, 0.9,
		   12.0, 8.0, 4.0, 3.0, 0.75,
		   1.0, 0.05,
		  ),
		  (
		   'green', libswarm.EnergyBall, 100,
		   8, 2.5,
		   (0.0, 0.9, 0.0), (0.0, 0.8, 0.0), 100, 0.9,
		   8.0, 6.0, 4.0, 3.0, 0.75,
		   1.0, 0.05,
		  ),
		  (
		   'blue', libswarm.EnergyBall, 100,
		   8, 2.5,
		   (0.0, 0.0, 0.9), (0.0, 0.0, 0.8), 100, 0.9,
		   10.0, 7.0, 4.0, 3.0, 0.75,
		   1.0, 0.05,
		  ),
		 )
		)
		self._bg_layer.randomizeBallLocations()
		self._bg_layer.randomizeBallVelocities(x_range=10.0, y_range=10.0)
		
		glDisable(GL_DEPTH_TEST)
		glClearColor(0.0, 0.0, 0.0, 1.0)
		
		self._fps_display = pyglet.clock.ClockDisplay(format="%(fps).1fFPS")
		
	def tick(self):
		self._bg_layer.tick()
		
	def draw(self):
		self.clear()
		
		self._bg_layer.draw()
		
		#Render the current FPS.
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		gluOrtho2D(0.0, self.width, 0.0, self.height)
		glMatrixMode(GL_MODELVIEW)
		glLoadIdentity()
		self._fps_display.draw()
		
		self.flip()
		
	def on_draw(self):
		pass
		
	def on_mouse_release(self, x, y, button, modifiers):
		if button == pyglet.window.mouse.LEFT:
			self._bg_layer.summon(x, 720 - y, 'red')
		elif button == pyglet.window.mouse.RIGHT:
			self._bg_layer.unsummon('red')
		else:
			self._bg_layer.group()
			
if __name__ == '__main__':
	demo = _Demo(1280, 720)
	
	pyglet.clock.set_fps_limit(30.0)
	while not demo.has_exit:
		pyglet.clock.tick()
		demo.dispatch_events()
		demo.tick()
		demo.draw()
		
